import numpy as np
import pandas as pd
from tensorflow.keras.models import load_model
from tensorflow.core.protobuf.config_pb2 import ConfigProto
from tensorflow.python.client.session import Session
from keras_preprocessing.image import ImageDataGenerator
# 这个是用来预测测试集的水稻是什么病害

# 控制gup
config = ConfigProto()
config.gpu_options.per_process_gpu_memory_fraction = 0.5  #占用85%显存
session = Session(config=config)

# 加载模型
model = load_model('saved_model/my_model03.h5')

# 基础数据
img_rows, img_cols = 256, 256
batch_size = 100
test_loc = 'input/paddy-disease-classification/test_images'
test_data = ImageDataGenerator(rescale=1.0/255).flow_from_directory(
    directory=test_loc,
    target_size=(img_rows, img_cols),
    batch_size=batch_size,
    classes=['.'],
    shuffle=False,
)

aug_gens = ImageDataGenerator(
    rescale=1.0/255.0,
    featurewise_center=False,
    samplewise_center=False,
    featurewise_std_normalization=False,
    samplewise_std_normalization=False,
    zca_whitening=False,
    validation_split=0.1,
    rotation_range=10,
    shear_range=0.25,
    zoom_range=0.1,
    width_shift_range=0.1,
    height_shift_range=0.1,
    horizontal_flip=True,
    vertical_flip=True,
)
train_loc = 'input/paddy-disease-classification/train_images/'
train_data = aug_gens.flow_from_directory(
    train_loc,
    subset="training",
    seed=2,
    target_size=(img_rows, img_cols),
    batch_size=batch_size,
    class_mode="categorical")


# 评估
evaluate_test = model.evaluate(test_data, verbose=1)
# print("\nAccuracy =", "{:.7f}%".format(evaluate_test[1]*100))
# print("Loss     =" ,"{:.9f}".format(evaluate_test[0]))

y_pred = model.predict(test_data)
# np.argmax()是numpy中获取array的某一个维度中数值最大的那个元素的索引
# axis=1指定代表我要查找的最大元素在第1维中的索引值
y_predict_max = np.argmax(y_pred,axis=1)    # 转换为预测标签


# 提交保存结果到本地
inverse_map = {v:k for k,v in train_data.class_indices.items()}

predictions = [inverse_map[k] for k in y_predict_max]

files=test_data.filenames

results=pd.DataFrame({"image_id":files,
                      "label":predictions})
results.image_id = results.image_id.str.replace('./', '')
results.to_csv("submission_new.csv",index=False)